#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动实时评估系统
"""

import subprocess
import sys
import os
import time
import threading
import webbrowser
from pathlib import Path

def start_api_server():
    """启动API服务器"""
    print("启动API服务器...")
    try:
        subprocess.run([sys.executable, 'api_server.py', '--port', '8002'], 
                      cwd=os.path.dirname(os.path.abspath(__file__)))
    except KeyboardInterrupt:
        print("API服务器已停止")

def start_web_server():
    """启动Web服务器"""
    print("启动Web服务器...")
    try:
        subprocess.run([sys.executable, 'start_server.py'], 
                      cwd=os.path.dirname(os.path.abspath(__file__)))
    except KeyboardInterrupt:
        print("Web服务器已停止")

def main():
    """主函数"""
    print("=" * 60)
    print("启动实时评估系统")
    print("=" * 60)
    
    # 检查必要文件
    required_files = ['api_server.py', 'start_server.py', 'monitor.py', 'ai_evaluator.py']
    for file in required_files:
        if not Path(file).exists():
            print(f"[ERROR] 缺少必要文件: {file}")
            return 1
    
    print("所有必要文件检查通过")
    
    # 启动API服务器（后台线程）
    api_thread = threading.Thread(target=start_api_server, daemon=True)
    api_thread.start()
    
    # 等待API服务器启动
    print("等待API服务器启动...")
    time.sleep(3)
    
    # 启动Web服务器
    print("启动Web服务器...")
    print("\n访问地址:")
    print("  主页: http://localhost:8001/index.html")
    print("  实时评估: http://localhost:8001/realtime_eval.html")
    print("  薪资详情: http://localhost:8001/salary_detail.html")
    print("  API状态: http://localhost:8002/api/health")
    print("\n按 Ctrl+C 停止所有服务")
    
    # 延迟打开浏览器
    def open_browser():
        time.sleep(2)
        webbrowser.open('http://localhost:8001/realtime_eval.html')
    
    browser_thread = threading.Thread(target=open_browser, daemon=True)
    browser_thread.start()
    
    try:
        start_web_server()
    except KeyboardInterrupt:
        print("\n正在停止服务...")
        return 0

if __name__ == '__main__':
    sys.exit(main())
